package io.github.smileinmotion.oplog.util;


import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * des: Request IP
 *
 * @author Mr.spc
 * @version 1.0
 * @since 2025-06-03 16:22:51
 */
public class IpUtils {

    /**
     * des:获取ip
     *
     * @param request request
     * @return String ip
     */
    public static String getIp(HttpServletRequest request) {
        String unknown = "unknown";
        String ipStr = request.getHeader("x-forwarded-for");
        if (StrUtil.isBlank(ipStr) || unknown.equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ipStr) || unknown.equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrUtil.isBlank(ipStr) || unknown.equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StrUtil.isBlank(ipStr) || unknown.equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StrUtil.isBlank(ipStr) || unknown.equalsIgnoreCase(ipStr)) {
            ipStr = request.getRemoteAddr();
        }
        if (StrUtil.isNotBlank(ipStr) && ipStr.contains("0:0:0:0:0:0:0:1")) {
            ipStr = "127.0.0.1";
        }
        String[] split = ipStr.split(",");
        for (String str : split) {
            if (!unknown.equalsIgnoreCase(str)) {
                ipStr = str;
                break;
            }
        }
        return ipStr;
    }
}
